<template>
  <view class="chat-container">
    <view class="chat-header">
      <!-- <view class="back-btn" @click="goBack">返回</view> -->
      <view class="chat-title" style="flex: 1; text-align: center;">{{currentChat.sender}}</view>
    </view>
    
    <scroll-view class="chat-messages" scroll-y="true">
      <view v-for="(msg, index) in messages" :key="index" class="message-item" :class="msg.isMe ? 'sent' : 'received'">
        <image v-if="!msg.isMe" class="user-avatar" :src="currentChat.avatar"></image>
        <view class="message-container">
          <view v-if="!msg.isMe" class="sender-name">{{currentChat.sender}}</view>
          <view class="message-content" :class="msg.isMe ? 'sent' : 'received'">{{msg.content}}</view>
          <view class="message-time">{{msg.time}}</view>
        </view>
        <image v-if="msg.isMe" class="user-avatar" src="../../static/首页.png" @click="goToUser"></image>
      </view>
    </scroll-view>
    
    <view class="chat-input">
      <image class="emoji-icon" src="../../static/笑脸.jpg" @click="showEmojiPicker"></image>
      <input class="input-box" v-model="inputText" placeholder="输入消息..." />
      <button class="send-btn" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script>
let socketTask;

export default {
  data() {
    return {
      currentChat: {
        sender: '用户A',
        avatar: '../../static/章若楠.png'
      },
      messages: [
        { content: '你好，有空吗？', time: '14:30', isMe: false },
        { content: '有的，有什么事吗？', time: '14:32', isMe: true }
      ],
      inputText: ''
    };
  },
  mounted() {
    // 建立 WebSocket 连接
    socketTask = wx.connectSocket({
      url: 'ws://127.0.0.1:8080/websocket/message?token='+uni.getStorageSync("App-Token"),
      success: () => {
        console.log('WebSocket 连接请求已发送');
      }
    });

    socketTask.onOpen(() => {
      console.log('WebSocket 连接已建立');
    });

    socketTask.onError((error) => {
      console.error('WebSocket 发生错误:', error);
    });

    socketTask.onClose(() => {
      console.log('WebSocket 连接已关闭');
    });

    socketTask.onMessage((res) => {
      try {
        const message = JSON.parse(res.data);
        this.messages.push({
          ...message,
          isMe: false
        });
      } catch (error) {
        console.error('解析消息失败:', error);
      }
    });},
  
  beforeDestroy() {
    // 组件销毁前关闭 WebSocket 连接
    if (socketTask) {
      console.log('正在关闭 WebSocket 连接...');
      socketTask.close();
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    sendMessage() {
      if (this.inputText.trim() && socketTask && socketTask.readyState === 1) {
        const message = {
          content: this.inputText,
          time: new Date(),
          isMe: true,
		  sendToUserId:"101"
        };
        this.messages.push(message);
        // 发送消息到 WebSocket
        try {
          socketTask.send({
            data: JSON.stringify(message),
            success: () => {
              console.log('消息发送成功');
            },
            fail: (error) => {
              console.error('消息发送失败:', error);
              // 可以在这里添加提示用户的逻辑，如弹出提示框
            }
          });
        } catch (error) {
          console.error('发送消息时出错:', error);
        }
        this.inputText = '';
      } else if (this.inputText.trim()) {
        console.error('WebSocket 连接未就绪，无法发送消息');
      }
    },
    goToUser() {
      uni.switchTab({
        url: '/pages/user/user'
      });
    }
  }
};
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(to bottom, #e6f2ff, #f0f7ff);
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: linear-gradient(to right, #55aaff, #66bbff);
  color: white;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.back-btn {
  margin-right: 20rpx;
  color: white;
}

.chat-title {
  font-size: 32rpx;
  font-weight: bold;
}

.chat-messages {
  flex: 1;
  padding: 20rpx;
  background-color: #e6f2ff;
}

.message-item {
  margin-bottom: 20rpx;
  display: flex;
  align-items: flex-start;
}

.message-item.received {
  justify-content: flex-start;
}

.message-item.sent {
  justify-content: flex-end;
}

.message-container {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.sender-name {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 5rpx;
}

.message-item.received {
  justify-content: flex-start;
}

.message-item.sent {
  justify-content: flex-end;
}

.message-content {
  padding: 15rpx 20rpx;
  border-radius: 10rpx;
  display: inline-block;
}

.message-content.received {
  background-color: white;
  color: #333;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.08);
  position: relative;
}

.message-content.sent {
  background: linear-gradient(to right, #55aaff, #66bbff);
  color: white;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.message-content.received {
  background-color: white;
  color: #333;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.08);
  position: relative;
}

.message-content.sent {
  background: linear-gradient(to right, #55aaff, #66bbff);
  color: white;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.message-time {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
  text-align: center;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin: 0 15rpx;
  border: 2rpx solid rgba(255,255,255,0.8);
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
}

.chat-input {
  display: flex;
  padding: 20rpx;
  background-color: white;
  border-top: 1px solid #eee;
  align-items: center;
}

.emoji-icon {
  width: 50rpx;
  height: 50rpx;
  margin-right: 20rpx;
}

.input-box {
  flex: 1;
  padding: 15rpx;
  border: 1px solid #ddd;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.send-btn {
  background: linear-gradient(to right, #55aaff, #66bbff);
  color: white;
  border-radius: 10rpx;
  padding: 0 30rpx;
  height: 70rpx;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
}
</style>